package org.example.controller;

import org.example.pojo.domain.User;
import org.example.pojo.dto.UserRegistrationDto;
import org.example.properties.JwtProperties;
import org.example.result.Result;
import org.example.service.UserService;
import org.example.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/auth")
@RestController
@CrossOrigin
public class AuthController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    // 注册
    @PostMapping("/register")
    public Result register(@RequestBody UserRegistrationDto registrationDto) {
        try {
            userService.registerUser(registrationDto);
            return Result.success("用户注册成功!");
        } catch (RuntimeException e) {
            return Result.error("用户注册失败: " + e.getMessage());
        }
    }

    // 登录
    @PostMapping("/login")
    public Result login(@RequestParam String username, @RequestParam String password,@RequestParam String role) {
        try {
            User user = userService.loginUser(username, password,role);
            // 登录成功后，生成jwt令牌
            Map<String,Object> claims = new HashMap<>();
            claims.put("role",user.getRole());
            claims.put("id",user.getUserId());
            claims.put("username",user.getUsername());
            //生成token
            String token = JwtUtil.createJWT(
                    jwtProperties.getSecretKey(),
                    jwtProperties.getTime(),
                    claims);
            claims.put("token",token);

            return Result.success("用户登录成功！", claims);  // 返回用户数据
        } catch (RuntimeException e) {
            return Result.error("用户登录失败: " + e.getMessage());
        }
    }
}
